package com.example.myjavafx.controller;

import com.example.myjavafx.model.User;
import com.example.myjavafx.model.Users;
import com.example.myjavafx.service.ApiService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class MainController {
    @FXML
    private Button videoPlayerBtn;

//    @FXML
//    public VBox contentArea;
    @FXML
    private TableView<User> userTable;

    @FXML
    private Label loadingLabel;

    @FXML private Label titleLabel;
    /**
     * 当前页面的标题
     */
    private String currentTitle = "";
    @FXML private StackPane contentArea;
    @FXML private BorderPane contentPane;

    /**
     * 已加载的页面节点缓存，用于快速切换已显示的页面
     */

    private Map<String, Node> contentCache = new HashMap<>();

    /**
     * 初始化操作
     */
    @FXML
    private void initialize() {
        // 初始化将contentArea设置为contentPane的中心节点，并设置标题标签的鼠标点击事件，用于切换已显示的页面
        contentPane.setCenter(contentArea);
        titleLabel.setOnMouseClicked(event -> {
            if (contentCache.containsKey(currentTitle)) {
                Node cachedNode = contentCache.get(currentTitle);
                contentPane.setCenter(cachedNode);
            }
        });
        showHome(); // 默认显示首页
    }

    @FXML
    private void showVideoPlayer() {
        loadContent("video-player.fxml", "视频播放");
    }

    @FXML
    private void showHome() {
        loadContent("home.fxml", "首页");
    }

    @FXML
    private void showProducts() {
        loadContent("products.fxml", "产品管理");
    }

    @FXML
    private void showOrders() {
        loadContent("orders.fxml", "订单管理");
    }

    @FXML
    private void showSettings() {
        loadContent("settings.fxml", "系统设置");
    }

    @FXML
    private void showSentimentAnalysis() {
        loadContent("sentiment-analysis.fxml", "情感分析");
    }

    @FXML
    private void showLightSource() {
        loadContent("light-source.fxml", "光源控制");
    }

    @FXML
    private void showCameraControl() {
        loadContent("camera-control.fxml", "相机控制");
    }

    @FXML
    private void showPersonnelSearch() {
        loadContent("personnel-search.fxml", "人员搜索");
    }
    @FXML
    private void imageDisplay() {
        loadContent("ImageDisplayView.fxml", "相机采图");
    }

    private void loadContent(String fxmlFile, String title) {
        try {
            Node cachedNode = contentCache.get(title);
            if (cachedNode == null) {
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/example/myjavafx/" + fxmlFile));
                cachedNode = loader.load();
                contentCache.put(title, cachedNode);
            }
//            FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/example/myjavafx/" + fxmlFile));
//            contentArea.getChildren().clear();
//            contentArea.getChildren().add(loader.load());
            contentPane.setCenter(cachedNode);
            titleLabel.setText(title);
            currentTitle = title;

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private final ObservableList<Users> users = FXCollections.observableArrayList();

    // 初始化
//    @FXML
//    public void initialize() {
//        // 绑定表格数据源
////        userTable.setItems(users);
//
//        // 进入主页面时自动加载数据
////        loadData();
//    }

    // 接收从登录页传递的用户名
    public void setUsername(String username) {
        loadingLabel.setText("欢迎，" + username + "！");
    }

    @FXML
    private void handleLogout() {
        // 返回到登录页（或关闭应用）
        try {
            Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/com/example/myjavafx/login-view.fxml")));
            Stage stage = (Stage) loadingLabel.getScene().getWindow();
            stage.setScene(new Scene(root, 400, 300));
            stage.setTitle("用户登录");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadData() {
        // 显示加载提示
        loadingLabel.setVisible(true);
        userTable.setVisible(false);

//        ApiService.getUsers().forEach(user -> {
////            users.add(user);
//            users.setAll(user);
//            loadingLabel.setVisible(false);
//            userTable.setVisible(true);
//        });

         //调用API获取数据
        ApiService.fetchUsers(
                // 成功回调
                data -> {
                    users.setAll(data);
                    loadingLabel.setVisible(false);
                    userTable.setVisible(true);
                },
                // 失败回调
                error -> {
                    loadingLabel.setText("加载失败: " + error);
                }
        );
    }

    @FXML
    public void handleMenuItem1(ActionEvent actionEvent) {

    }
    @FXML
    public void handleMenuItem2(ActionEvent actionEvent) {
    }
    @FXML
    public void handleMenuItem3(ActionEvent actionEvent) {
    }
    @FXML
    public void handleMenuItemExit(ActionEvent actionEvent) {
    }
}